package com.example.futureai.config.mcp;

import com.example.futureai.annotation.McpService;
import com.example.futureai.mcp.StudentMcp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: ToolCallbackProviderConfig
 * @Description:
 * @Author: YourName
 * @Date: 2025/11/6
 */
@Configuration
@Slf4j
public class ToolCallbackProviderConfig {
    @Bean
    public ToolCallbackProvider toolCallbackProvider(ApplicationContext context) {
        // 自动收集所有 MCP 服务
        Map<String, Object> mcpServices = context.getBeansWithAnnotation(McpService.class);

        if (mcpServices.isEmpty()) {
            // 如果没有找到注解的服务，尝试按命名约定查找
            mcpServices = context.getBeansOfType(Object.class).entrySet().stream()
                    .filter(entry -> entry.getKey().endsWith("Mcp") || entry.getKey().endsWith("Service"))
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        }
        log.info("注册了 {} 个本地 MCP 服务: {}", mcpServices.size(), mcpServices.keySet());
        return MethodToolCallbackProvider.builder()
                .toolObjects(mcpServices.values().toArray())
                .build();
    }
}
